import { createSlice } from "@reduxjs/toolkit";

// createSlice用于创建一个包含了reducer和action的对象，用来创建一个仓库的模块
export const counterSlice = createSlice({
  // name表示模块的名称
  name: "counter",
  // initialState表示模块的初始状态
  initialState: {
    value: 10,
  },
  // reducers用来修改模块数据的同步方法
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

// 需要将reducer里面的函数从counterSlice.actions进行暴露
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// 异步函数是写在外面的，需要用到dispatch
export const incrementAsync = (amount) => (dispatch) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount));
  }, 1000);
};

// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched
// export const incrementAsync = (amount) => (dispatch) => {
//   setTimeout(() => {
//     dispatch(incrementByAmount(amount));
//   }, 1000);
// };

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state) => state.counter.value)`
// export const selectCount = (state) => state.counter.value;

// 并且将整个reducer进行暴露
export default counterSlice.reducer;
